<template>
	<view class="task_page">
		<NavigationTitle title="流程审批" style="color: #000;background: #fff;position: fixed;width: 100%;z-index: 5;">
			<template slot="left_con">
				<text></text>
				<!-- <image class="back_icon" src="@/static/common/back.png" mode="widthFix" @tap="backSelf" /> -->
			</template>
			<template slot="right_con">
				<uni-icons type="settings" size="30" @click="showDrawer()"></uni-icons>
			</template>
		</NavigationTitle>
		<view class="status-bar"></view>
		<view class="tab">
			<uni-data-checkbox style="margin-top: 8rpx;" mode="tag" v-model="radioKey" @change="changeTab" :localdata="[
				// {
				// 	text: '全部',
				// 	value: 2
				// },
				{
					text: '我的接收',
					value: 0
				},
				{
					text: '我的申请',
					value: 1
				}
			]"></uni-data-checkbox>
		</view>
		<scroll-view class="userList" scroll-y="true" @scrolltolower="scrolltoupper">
			<text id="a"></text>
			<view class="user_item" v-for="item in taskList" :key="item.userId"
				@click.stop.prevent="()=>callback('edit',item)">
				<view v-if="radioKey==1" class="item_top">
					<view class="title">流程名称：<text class="value">{{item.processName}}</text></view>
					<view class="title">审批状态：<text class="value">{{item.isCompleted==2?'已审批':'未审批'}}</text></view>
					<view class="title">执行状态：<text class="value">{{item.taskState==1?'已中止':'已激活'}}</text></view>
					<view class="title">申请时间：<text class="value">{{item.applicantDateTime}}</text></view>
					<view class="title" >流程事由：<text class="value">{{item.reason}}</text></view>
					<view class="title" v-if="item.processDefinitionKey!='notice'">文件名称：<text class="value">{{item.fileName}}</text></view>
				</view>
				<view v-if="radioKey==0" class="item_top">
					<view class="title">任务名称：<text class="value">{{item.taskName}}</text></view>
					<view class="title">流程名称：<text class="value">{{item.processName}}</text></view>
					<view class="title">执行状态：<text class="value">{{item.taskState==1?'已中止':'已激活'}}</text></view>
					<view class="title">待审批人：<text class="value">{{item.assignee||''}}</text></view>
					<view class="title">申请人：<text class="value">{{item.starter}}</text></view>
					<view class="title">申请时间：<text class="value">{{item.createTime}}</text></view>
					<view class="title">流程事由：<text class="value">{{item.reason}}</text></view>
					<view class="title"  v-if="item.processDefinitionKey!='notice'">文件名称：<text class="value">{{item.fileName}}</text></view>
					<!-- <button size="mini" class="changeBtn" >变更审批人</button> -->
				</view>
				<view v-if="radioKey==2" class="item_top">
					<view class="title">流程名称：<text class="value">{{item.processName}}</text></view>
					<view class="title">审批状态：<text class="value">{{item.isCompleted==2?'已审批':'未审批'}}</text></view>	
					<view class="title">申请人：<text class="value">{{item.applicant}}</text></view>
					<view class="title">申请时间：<text class="value">{{item.applicantDateTime}}</text></view>
				</view>
				<view class="item_bottom" v-if="radioKey==0">
					<button size="mini" class="item_btn" @click.stop.prevent="()=>callback('change',item)">变更审批人</button>
					<!-- <button size="mini" class="item_btn" style="color: red;" @click.stop.prevent="()=>callback('delete',item)">删除</button> -->
				</view>
			</view>
			<view v-if="taskList.length==0" class="noData">暂无数据</view>
			<uni-load-more :status='loadStatus' v-if="taskList&&taskList.length!=0"></uni-load-more>
		</scroll-view>
		<uni-drawer ref="showLeft" mode="left" :width="320">
			<view class="status-bar"></view>
			<view class="drawerLeft">
				<uni-forms ref="baseForm" :modelValue="searchValue" label-position="top" class="baseForm">
					<uni-forms-item label="流程名称:">
						<uni-easyinput v-model="searchValue.taskName" placeholder="请输入流程名称" />
					</uni-forms-item>
				</uni-forms>
				<view class="popupBtn">
					<button type="primary" @click="drawerConfirm" class="btn">确定</button>
					<button type="reset" @click="drawerClose" class="btn">重置</button>
				</view>
			</view>
		</uni-drawer>
		<uni-popup ref="popup" background-color="#fff">
			<button  size="default" style="color: deepskyblue;width: 40%;margin:10rpx auto;" @click="subUser">提交</button>
			<view class="popup-content">
				<DaTreeVue2 ref="DaTreeRef" :data="userTree" labelField="title" valueField="id" defaultExpandAll
					 :defaultCheckedKeys="defaultCheckedKeysValue" @change="handleTreeChange" />
			</view>
		</uni-popup>
		<image v-if="authorList.includes('system_task_add')" src="@/static/common/advice_add.png" class="userAdd" @click="addTask"></image>
	</view>
</template>

<script>
	import NavigationTitle from '@/components/navigationTitle'
	import DaTreeVue2 from '@/components/da-tree-vue2/index.vue'
	import {
		showToastMsg,
		showModalMsg,
	} from '@/utils/format.js'
	import {
		mapGetters,
		mapActions
	} from 'vuex'
	export default {
		components: {
			NavigationTitle,
			DaTreeVue2
		},
		computed: {
			...mapGetters(['project', 'projectId', 'authorList'])
		},
		data() {
			return {
				radioKey: 1,
				value: 'taskName',
				searchValue: {},
				option_search: [{
					value: 'taskName',
					text: "任务名称"
				}, ],
				taskId:"",
				userTree:[],
				defaultCheckedKeysValue: [],
				checkedKey:[],
				taskList: [],
				page: {
					current: 1,
					size: 10,
				},
				pullLoading: false,
				loadingType: 0, //加载状态
				isLoadingMore: false, // 是否正在加载更多
				loadStatus: 'more', // 是否还有更多数据
			}
		},
		// onLoad(){
		// 	this.getTaskList(this.page)
		// },
		onShow() {
			this.taskList = []
		
			this.getTaskList({
				current: 1,
				size: 10,
			})
		},
		methods: {
			...mapActions(['save_task']),
			
			async getUserList() {
				const res = await this.$api.getUserlist({
					projectId: this.projectId
				}).catch(err => {
					console.log(err)
				})
				if (res?.code == 200 && res.data.length != 0) {
					this.userTree = res.data
				}
			},
			backSelf() {
				uni.redirectTo({
					url:'/pages/index/index'
				})
				// uni.navigateBack({
				// 	delta: 1
				// })
			},
			changeTab(e) {
				this.searchValue = {}
				this.getTaskList({
					current: 1,
					size: 10,
				}, null)
			},
			showDrawer() {
				if (this.radioKey == 1 ||this.radioKey == 2	) return
				this.$refs['showLeft'].open()
			},
			// 关闭窗口
			closeDrawer() {
				this.$refs['showLeft'].close()
			},
			drawerConfirm() {
				// this.$refs.baseForm.validate().then(res=>{
				// 	console.log(res)
				// })
				this.getTaskList({
					current: 1,
					size: 10,
				}, this.searchValue)
				this.closeDrawer()
			},
			drawerClose() {
				this.searchValue = {}
				this.getTaskList({
					current: 1,
					size: 10,
				}, null)
				this.closeDrawer()
			},
			goDetail(data) {
				if(this.radioKey==2) return 
				this.save_task(data)
				let key=null
				if(this.radioKey==1&&data.isCompleted==1&&data.taskState==1){
					//我的申请里未审批的已中止的流程
					key = '1'
					
				}else if(this.radioKey==1&&data.isCompleted==1&&data.taskState==2){
					//我的申请里未审批的已激活的流程
					key = '2'
				}
				else if(this.radioKey==1&&data.isCompleted==2){
					//我的申请里已审批的流程
					key = '3'
				}else if(this.radioKey==0&&data.taskState==1){
					//待办里已中止的任务
					key = '4'
				}else if(this.radioKey==0&&data.taskState==2){
					//待办里已激活的任务
					key = '5'
				}else key='0'
				uni.navigateTo({
					url: '/pages/approve/detail?type=edit&key='+key+'&taskId=' + data.taskId
				})
			},
			scrolltoupper() {
				let page = {
					current: this.page.current + 1,
					size: 10,
				}
				this.page = page
				this.getListMore(page, this.searchValue)
			},
			addTask() {
				uni.navigateTo({
					url: '/pages/approve/detail?type=add'
				})
			},

			async getTaskList(page, value) {
				let that = this,
					param = {},
					res = null
				let {
					current,
					size
				} = JSON.parse(JSON.stringify(page))
				param.pageNum = current
				param.pageSize = size
				this.taskList = []
				if (value) {
					for (let key in value) {
						param[key] = value[key]
					}
				}
				
				if (this.radioKey == 0) {
					param.projectId=this.projectId
					res = await this.$api.getTaskList(param)
				} else if (this.radioKey == 1) {
					
					res = await this.$api.getMyTaskList(param)
				}else if(this.radioKey==2){
					res = await this.$api.getTaskListAll(param)
				}
				if (res?.code == 200&&res.data.data) {
					this.taskList = res.data.data
					this.page = page
					if(res.data.data.length<size){
						this.loadingType = 2;
						this.loadStatus = "noMore"
					}
				}
				setTimeout(() => {
					that.pullLoading = false;
				}, 500)

			},
			async getListMore(page, value) {
				if (this.loadingType !== 0) return
				this.loadStatus = "loading"
				uni.showLoading({
					title: "加载中...",
					mask: true
				})
				this.loadingType = 1
				let {
					current,
					size
				} = JSON.parse(JSON.stringify(page)),
				param = {
					pageSize:size,
					pageNum:current,
				},res = null
				if (value) {
					for (let key in value) {
						param[key] = value[key]
					}
				}
				if (this.radioKey == 0) {
					param.projectId=this.projectId
					res = await this.$api.getTaskList(param)
				} else if (this.radioKey == 1) {
					
					res = await this.$api.getMyTaskList(param)
				}else if(this.radioKey==2){
					res = await this.$api.getTaskListAll(param)
				}
				if (res?.code == 200) {
					if (res.data.data.length == 0) {
						this.loadingType = 2;
						this.loadStatus = "noMore"
						return
					} else if (res.data.data.length < size) {
						this.loadingType = 2;
						this.loadStatus = "noMore"
					} else {
						this.loadingType = 0;
						this.loadStatus = "more"
					}
					this.taskList = this.taskList.concat(res.data.data)
					this.page = page
					uni.hideLoading()
				}
			},
			changeSel(e) {
				this.value = e
			},
			callback(type, data) {
				if (type == 'edit') this.goDetail(data)
				else if (type == 'change') this.changeTransfer(data)
				// else if (type == 'delete') this.delUser(data)
			},
			async changeTransfer(data){
				if(!this.authorList.includes('system_file_edit'))  return showToastMsg('没有编辑权限，需申请权限!')
				this.taskId = data.taskId
				await this.getUserList()
				if (this.userTree.length == 0) this.userTree = []
				else {
					this.userTree.map(v => {
						if (v.userList.length > 0) {
							v.id=v.companyId
							v.title = v.companyName
							v.userList.map(i => {
								if(v.children==undefined) v.children=[]
								v.children.push({
									id: v.companyId + '-' + i.userId,
									title: i.nickName
								})
							})
						}
					})
				}
				console.log(this.userTree, this.defaultCheckedKeysValue)
				this.$refs.popup.open('bottom')
			},
			handleTreeChange(allSelectedKeys, currentItem) {
				this.checkedKey = allSelectedKeys
			},
			async subUser() {
				if (!this.$refs.DaTreeRef?.getCheckedKeys()) return showToastMsg('请选择可见人员！')
				let arr = this.$refs.DaTreeRef?.getCheckedKeys()
				let keys = []
				arr.map(v => {
					let v_ = v.split('-')
					if (v_.length > 1) {
						keys.push(v_[1])
					}
				})
				const res = await this.$api.changeTransfer({
					taskId: this.taskId,
					userIdList: keys
				}).catch(err => {
					console.log(err)
				})
				if (res?.code == 200) {
					this.$refs.popup.close()
					this.searchValue = {}
					this.getTaskList({
						current: 1,
						size: 10,
					}, null)
				}
				showToastMsg(res.msg)
			},
			async delUser(data) {
				if (!this.authorList.includes('system_device_del')) return showToastMsg('无操作权限！')
				showModalMsg('', '是否确认从项目中移除本用户', async (val) => {
					if (val) {
						await this.$api.delEquipment(data.deviceId).then(res => {
							if (res?.code == 200) {
								this.getTaskList(this.page, null)
							}
							showToastMsg(res.msg)
						}).catch(err => {
							showToastMsg('请求失败！')
						})
					}

				})

			},
			getAssignee(str) {
				if (str) return str.slice(1, str.length - 1);
				else return ''

			},
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/assets/styles/global.scss';

	view {
		box-sizing: border-box !important;
	}

	.task_page {
		position: relative;
		height: 100%;
	}

	.user_search {
		display: flex;
		padding: $System__title_height 12rpx 0;

		.search {
			flex: 7;
		}

		/deep/.uni-stat__select {
			flex: 3;
		}
	}

	.tab {
		padding: $System__title_height 36rpx 0;

		/deep/ .checklist-text {
			font-size: 32rpx !important;
			padding: 10rpx 10rpx;
		}
	}

	.userList {
		height: calc(100vh - 250rpx);
		// padding: $System__title_height 0 0;
		position: relative;
		overflow: auto;
		/deep/ .uni-scroll-view-content {
			padding: 0 48rpx 20rpx;
			box-sizing: border-box !important;
			height: auto;
		}

		.noData {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			color: #999;
		}

		.user_item {
			min-height: 200rpx;
			background-color: #eee;
			margin-top: 24rpx;
			border-radius: 20rpx;
			padding: 24rpx;
			box-shadow: 0rpx 5rpx 10rpx 0rpx #F0F0F0;
			display: flex;
			flex-direction: column;
			justify-content: flex-end;

			.item_top {
				width: 100%;
				padding-left: 12rpx;
				font-size: 32rpx;
				.title {
					font-weight: 600;
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-bottom: 10rpx;
					.value {
						width: 73%;
						display: block;
						font-weight: normal;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}
				}
				.changeBtn{
					width: 100%;
					text-align: center;
					color: #2979ff;
				}
			}

			.item_bottom {
				display: flex;
				justify-content: center;

				.item_btn {
					width: 49%;
					margin-top: 24rpx;
					background-color: #2979ff;
					color: #fff;
				}
			}

		}
	}

	.back_icon {
		width: 37rpx;
	}

	.drawerLeft {
		padding: 20rpx;

		.baseForm {
			padding: 20rpx 0;
			min-height: 50vh;
		}

		.popupBtn {
			display: flex;
			justify-content: space-between;
			margin-top: 20rpx;

			.btn {
				width: 45%;
			}
		}
	}

	.userAdd {
		width: 150rpx;
		height: 150rpx;
		border-radius: 50%;
		position: fixed;
		bottom: 200rpx;
		right: 50rpx;
	}
	.popup-content {
		max-height: 1000rpx;
		min-height: 500rpx;
		overflow: auto;
	}
</style>